package cn.hl.hm.handler;

import java.io.BufferedReader;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.vizhuo.utils.DateUtil;

import cn.hl.hm.constants.AlipayConfig;
import cn.hl.hm.constants.OrderStatus;
import cn.hl.hm.constants.PayMethod;
import cn.hl.hm.entity.Coupon;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.Order;
import cn.hl.hm.entity.Push;
import cn.hl.hm.entity.UnifiedOrderRespose;
import cn.hl.hm.service.OrderService;
import cn.hl.hm.service.PushToAppIService;
import cn.hl.hm.util.alipay.AlipayCore;

/**
 * 支付宝APP支付handler
 * 
 * @author 大和
 *
 */
@Service
public class ZfbAppPayHandler extends PayHandler {

	private static final Logger logger = Logger.getLogger(ZfbAppPayHandler.class);
	@Autowired
    @Qualifier("alipayConfig")
    private AlipayConfig alipayConfig;
	@Autowired
    @Qualifier("alipayConfigIosQYB")
    private AlipayConfig alipayConfigIosQYB;
	
	@Autowired
	private OrderService orderService;

	@Autowired
	@Qualifier("pushToAppServiceImpl")
	private PushToAppIService pushToAppIService;

	/**
	 * 处理支付宝支付请求
	 */
	@Override
	public Map<String, String> handler(Map<String, String> payMap) {
		
		String orderCode = payMap.get("orderCode");
		String orderInfo = payMap.get("orderInfo");
		String iosFlag = payMap.get("iosFlag");
		String merId = payMap.get("merId");
		
		
		HashMap<String, String> map = new HashMap<String, String>(); ;
		Order orderParam = new Order();
		orderParam.setOrderCode(orderCode);
		List<Order> selectOrder = orderService.selectOrder(orderParam);
		if(selectOrder!=null&&selectOrder.size()>0){
			
			if(StringUtils.isNotBlank(orderInfo)){
				String slipayParams;
				try {
					AlipayConfig config = null;
					if (iosFlag.equals("1")) {
						config = alipayConfig;
					} else {
						config = alipayConfigIosQYB;

					}
					//logger.info(".....支付宝环境配置参数："+config.toString()+"签名方式： "+AlipayConstants.SIGN_TYPE_RSA2);
					slipayParams = AlipaySignature.rsa256Sign(orderInfo, config.privateKey, config.zfbCharset);
					
					
					map.put("orderCode", orderCode);
					map.put("sign", slipayParams);
					map.put("iosFlag", iosFlag);
					map.put("backUrl", config.backUrl);

					//入库sign
					Order orderUpParam = new Order();
					orderUpParam.setId(selectOrder.get(0).getId());
					orderUpParam.setSigns(slipayParams);
					orderUpParam.setIosPayFlag(iosFlag);
					int updateOrderById = orderService.updateOrderById(orderUpParam);
					if(updateOrderById>0){
						return map;
					}else {
						return null;
					}
				} catch (AlipayApiException e) {
					e.printStackTrace();
					return map;
				}
				
			}else {
				return map;
			}
			
		}else {
			return map;
		}
	}
	@Override
	protected void initHandler() {
		register(PayMethod.ALIPAY_SDK, ZfbAppPayHandler.class);
	}

	/**
	 * 回调请求
	 */
	@Override
	public Boolean callback(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("......[支付宝回调]开始......" );
			
			BufferedReader reader = request.getReader();
			String line = "";
			StringBuffer inputString = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			if (reader != null) {
				reader.close();
			}
			logger.info("......[支付宝回调]接收到的报文......" + inputString.toString());
			//String decode = URLDecoder.decode(inputString.toString());
			String decode =URLDecoder.decode(inputString.toString(), "utf-8");
			//URL解码
			logger.info("......[支付宝回调]接收到的报文URLDecoder解码后......" + decode);
			//编码 (不加这行会有乱码)
			String str = new String(decode.getBytes("UTF-8"), "utf-8");
			logger.info("......[支付宝回调]接收到的报文UTF-8->UTF-8解码后......" + str);
			
			Map<String, String> map = AlipayCore.str2map(str);
			
			
			
			String orderCode = map.get("out_trade_no");// 商户网站唯一订单号
			String userPaymentTime = map.get("gmt_payment");// 支付时间
			String paymentFlowAccount = map.get("trade_no");// 流水账号支付宝交易号
			String paymentNo = map.get("buyer_logon_id");// 支付账号买家支付宝账号
			String sign = map.get("sign");
			//查看订单iosPayFlag
			Order orderParam = new Order();
			orderParam.setOrderCode(orderCode);
			List<Order> selectOrder = orderService.selectOrder(orderParam);
			Order order = new Order();
			
			if (selectOrder != null && selectOrder.size() > 0) {
				order = selectOrder.get(0);
				AlipayConfig config = null;
				if (order.getIosPayFlag().equals("1")) {
					config = alipayConfig;
				} else {
					config = alipayConfigIosQYB;

				}
				//验证签名
				/*boolean rsaCheckContent = AlipaySignature.rsaCheckV1(map, config.publicKey, config.zfbCharset,AlipayConstants.SIGN_TYPE_RSA2);
			
				if(!rsaCheckContent){
					return false;
				}*/
			}else {
				return false;
			}
			
			 
			if(!map.get("trade_status").equalsIgnoreCase("TRADE_SUCCESS")){
				return false;
			}
			logger.info("......[支付宝验签结果成功]+[交易状态成功]......");
			UnifiedOrderRespose unifiedOrderRespose = new UnifiedOrderRespose();
			unifiedOrderRespose.setTime_end(userPaymentTime);
			unifiedOrderRespose.setTransaction_id(paymentFlowAccount);
			unifiedOrderRespose.setOpenid(paymentNo);
			unifiedOrderRespose.setOut_trade_no(orderCode);
			unifiedOrderRespose.setSign(sign);
			return processBusiness( unifiedOrderRespose);
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;

		}

	}

	private Boolean processBusiness(UnifiedOrderRespose unifiedOrderRespose) {
		// 查订单
		Order orderParam = new Order();
		orderParam.setOrderCode(unifiedOrderRespose.getOut_trade_no());
		List<Order> selectOrder = orderService.selectOrder(orderParam);
		Order order = new Order();
		if (selectOrder != null && selectOrder.size() > 0) {
			order = selectOrder.get(0);
			logger.info("......[支付宝回调]开始处理业务......unifiedOrderRespose"+unifiedOrderRespose.toString());

			if (order.getOrderStatus().equals(OrderStatus.TO_PAY.getStatus())) {
				String userPaymentTime = unifiedOrderRespose.getTime_end();// 支付时间
				logger.info("支付时间" + userPaymentTime);
				if (userPaymentTime != null && !("null".equals(userPaymentTime))) {

				} else {
					userPaymentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				}
				Date string2Date = DateUtil.string2Date(userPaymentTime, "yyyy-MM-dd HH:mm:ss");
				logger.info("......转换后支付时间" + string2Date);

				// 1 修改订单
				Order orderUpParam = new Order();
				orderUpParam.setId(order.getId());
				orderUpParam.setOrderStatus(OrderStatus.TO_ARRIVE.getStatus());
				orderUpParam.setPayTime(string2Date);
				orderUpParam.setPaymentNo(unifiedOrderRespose.getOpenid());
				orderUpParam.setPayTransNo(unifiedOrderRespose.getTransaction_id());
				orderUpParam.setPayType(PayMethod.ALIPAY_SDK.getCode());
				logger.info("......[支付宝回调]更新订单参数......orderUpParam"+orderUpParam.toString());
				int updateOrderById = orderService.updateOrderById(orderUpParam);
				if (updateOrderById > 0) {
					////////
					// 查询优惠券
					List<Coupon> tce = null;
					logger.info("支付宝支付回掉更改优惠券");
					if (StringUtils.isNotBlank(order.getPersonalCode())) {
						Map<String, String> map1 = new HashMap<>();
						Coupon cpParam = new Coupon();
						cpParam.setUserAccount(order.getSenderPhone());
						cpParam.setCouponCode(order.getPersonalCode());
						tce = orderService.selectCoupon(cpParam);
						if (tce != null & tce.size() > 0) {
							Coupon cpUpdateParam = new Coupon();
							cpUpdateParam.setId(tce.get(0).getId());
							cpUpdateParam.setStatus("1");
							cpUpdateParam.setUseTime(new Date());
							int updateCoupon = orderService.updateCoupon(cpUpdateParam);
							if (updateCoupon > 0) {
								return true;
							} else {
								return false;
							}
						} else {
							return true;
						}
					}
					// push to driver
					Driver driverSelectParam = new Driver();
					driverSelectParam.setId(order.getDriverId());

					List<Driver> driverList = orderService.selectDriver(driverSelectParam);
					if (driverList != null && driverList.size() > 0) {
						Driver driver = driverList.get(0);

						if (StringUtils.isNotBlank(driver.getDeviceToken())) {
							Push push = new Push();
							push.setPtype(1);
							push.setPushoid(order.getOrderCode());
							push.setContext("订单支付成功，已收到款项" + order.getPayPrice() + "元");// 要发送的内容
							push.setDisplayType("notification");// message:
																// 消息，通知：notification
							push.setOperationType(1);// 用户类型：1司机，2发货端
							push.setPushClient("driverPushClient");// 使用的推送Client
																		// 是往发货端：consignerPushClient
																		// 或
																		// 司机端发送：driverPushClient。
							push.setPushType("listcast");// unicast：单播
															// //
															// listcast：列表
							push.setTitle("订单支付成功"); // 发送的标题
							push.setTokenStr(new String[] { driver.getDeviceToken() }); // 要发送手机的token
							// ios & android推送公共调用方法
							pushToAppIService.pushCommon(push);
						}

					}

					return true;

				} else {
					return false;
				}

			} else {
				logger.info("......订单"+order.getOrderCode()+"...状态 "+order.getOrderStatus()+"...不处理 返回true");

				return true;
			}

		} else {
			return false;
		}
	}

}
